class ComputersController < ApplicationController
	# GET /computers
	# GET /computers.xml
	before_filter :check_authentication, :only => [:edit, :delete, :update]
	def index
		@computers = Computer.all

		respond_to do |format|
			format.html # index.html.erb
			format.xml  { render :xml => @computers }
		end
	end

	# GET /computers/1
	# GET /computers/1.xml
	def show

		begin
			@computer = Computer.find(params[:id])

			av_update = BaseVirale.find_by_computer_id(params[:id],
														:conditions => 'last_update IS NOT NULL')

			# format date
			if av_update
				av_update_date = av_update.last_update.in_time_zone.to_s(:db)
				date_tab = av_update_date.split(' ')
				year, month, day = date_tab[0].split("-")
				@av_update_date = "#{day}/#{month}/#{year} #{date_tab[1]}"
				#@date.strftime
			end

			# If riddance room's computer
			if @computer.room_id.to_i == 0
				riddance_tab = {:name => "Stock"}
				riddance = Room.new(riddance_tab)
				@computer.room = riddance
			end
			
			@events = TypeEvent.find(:all,
									:joins => "INNER JOIN events ON type_events.id = events.type_event_id
											  INNER JOIN computers ON computers.id = events.computer_id
											  INNER JOIN rooms ON rooms.id = computers.room_id",
									:from => "type_events",
									:conditions => ["computers.id = ?", params[:id]],
									:select => "type_events.name as type_event, events.updated_at as date_resolution, events.created_at as date_creation, events.information as event_info, events.state as state_event "
							)
		rescue
			@error = true
		end

		respond_to do |format|
			format.html # show.html.erb
			format.xml  { render :xml => @computer }
		end
	end

	# GET /computers/new
	# GET /computers/new.xml
	def new
		@params = params
		@room_id = params[:room]

		@computer = Computer.new

		###############VIRTUAL RIDDANCE ROOM################
		# Generate rooms list
		@rooms = Room.find(:all);

		# Add virtual riddance room
		riddance_tab = {:name => "Stock"}
		riddance = Room.new(riddance_tab)
		riddance.id = "0"
		@rooms << riddance
		####################################################

		respond_to do |format|
			format.html # new.html.erb
			format.xml  { render :xml => @computer }
		end
	end

	# GET /computers/1/edit
	def edit
		begin
			@computer = Computer.find(params[:id])

			###############VIRTUAL RIDDANCE ROOM################
			# Generate rooms list
			@rooms = Room.find(:all);

			# Add virtual riddance room
			riddance_tab = {:name => "Stock"}
			riddance = Room.new(riddance_tab)
			riddance.id = "0"
			@rooms << riddance
			####################################################
		rescue
			@error = true
		end
	end

	# POST /computers
	# POST /computers.xml
	def create

		@computer = Computer.new(params[:computer])

		respond_to do |format|
			if @computer.save
				computer_n = Computer.find(:all,
											:limit => 1,
											:order => 'id DESC')
				bv_datas = {:antivirus_id => @computer.software_id,
							:computer_id => computer_n[0].id};
				base_virales = BaseVirale.new(bv_datas)
				base_virales.save!
				
				flash[:notice] = 'L\'ordinateur a bien été créé.'
				format.html { redirect_to(@computer) }
				format.xml  { render :xml => @computer, :status => :created, :location => @computer }
			else
				format.html {

					####################################################
					# Prevent following issue
					# NoMethodError in Computers#create
					# 
					# Showing app/views/computers/new.html.erb where line #11 raised:
					#
					# You have a nil object when you didn't expect it!
					# You might have expected an instance of Array.
					# The error occurred while evaluating nil.collect

					# Generate rooms list
					@rooms = Room.find(:all);

					# Add virtual riddance room
					riddance_tab = {:name => "Stock"}
					riddance = Room.new(riddance_tab)
					riddance.id = "0"
					@rooms << riddance
					####################################################

					render :action => "new" }
				format.xml  { render :xml => @computer.errors, :status => :unprocessable_entity }
			end
		end
	end

	# PUT /computers/1
	# PUT /computers/1.xml
	def update
		@computer = Computer.find(params[:id])

		respond_to do |format|
			if @computer.update_attributes(params[:computer])
				av_update = BaseVirale.find_by_computer_id(params[:id])

				av_update.antivirus_id = @computer.software_id
				av_update.save!
				
				flash[:notice] = 'L\'ordinateur a bien été mis à jour.'
				format.html { redirect_to(@computer) }
				format.xml  { head :ok }
			else
				format.html { 

					###############VIRTUAL RIDDANCE ROOM################
					# Generate rooms list
					@rooms = Room.find(:all);

					# Add virtual riddance room
					riddance_tab = {:name => "Stock"}
					riddance = Room.new(riddance_tab)
					riddance.id = "0"
					@rooms << riddance
					####################################################
					
					render :action => "edit"
				}
				format.xml  { render :xml => @computer.errors, :status => :unprocessable_entity }
			end
		end
	end

	# DELETE /computers/1
	# DELETE /computers/1.xml
	def destroy
		@computer = Computer.find(params[:id])
		
		@computer.destroy
			
	
		respond_to do |format|
			format.html { redirect_to(computers_url) }
			format.xml  { head :ok }
			
		end
	end
def agent
  
    @computer = Computer.find(params[:id])
    percentAgent = 1+rand(100)
    if percentAgent <= 50
      state = 1
    else
      state = 0
    end
    
    if @computer.state_agent != state and state == 0
      @computer.update_attribute(:state_agent,state)
      event_tab = { "information" => "L'agent ne répond plus",
              "state" => 1,
              "computer_id" => @computer.id,
              "type_event_id" => 2
            }
      event = Event.new(event_tab)
      event.save
    elsif @computer.state_agent != state and state == 1
      @computer.update_attributes("state_agent"=>state)
     @event = Event.find(:first, :conditions => ["computer_id =? and information =? and state=?", @computer.id,"L'agent ne répond plus",1])
    logger.debug "The object is #{event}"
    record_tab = { "state"=>0}
     @event.update_attributes(record_tab)
    end
      
    #@cpu_used = (1 + rand(10)) * 10
    #@ram_used = (1 + rand(10)) * 10
    #@hard_drive_used = (1 + rand(10)) * 10
    
    
   # if  @hard_drive_used >= 70
      #type_event = 1
      #message = "Incident matériel : capacité disque dur à #{@hard_drive_used}%"
   # elsif @hard_drive_used >= 80
      #type_event = 2
      #message = "Incident matériel : capacité disque dur à #{@hard_drive_used}%"
    #elsif @hard_drive_used >= 90
      #type_event = 3
     # message = "Incident matériel : capacité disque dur à #{@hard_drive_used}%"
   # end
     
     
     #if  @ram_used >= 70
     # type_event = 1
     # message = "Incident matériel : utilisation de la ram à #{@ram_used}%"
    #elsif @ram_used >= 80
      #type_event = 2
      #message = "Incident matériel : utilisation de la ram à #{@ram_used}%"
    #elsif @ram_used >= 90
      #type_event = 3
      #message = "Incident matériel : utilisation de la ram à  #{@ram_used}%"
   # end
    
    #if  @cpu_used >= 100
      #type_event = 2
     # message = "Incident matériel : utilisation du cpu à #{@ram_used}%"
    
    #end
      # add event
      #if type_event
     # event_tab = { "information" => message,
            #  "state" => 1,
             # "computer_id" => @rand_record.id,
            #  "type_event_id" => type_event
           # }
     # event = Event.new(event_tab)


      #if event.save
      # puts "Un nouvelle incident a été détecté"
      #flash[:incident]= "Un nouvelle incident a été détecté"
      #end
     
    #end
    
    #record_tab = { "cpu" => @cpu_used,
                #   "ram_used" => @ram_used,
                #   "hard_drive_used" => @hard_drive_used
                # }
    #@computer.update_attributes(record_tab)
    
  
  respond_to do |format|
      format.html { redirect_to(@computer) }
      #format.xml  { render :xml => @computer }
      format.js{ render :update do |page|
        if state == 0
          icon="inactive"
        else
          icon="active"
        end
        page.replace "agent_state_#{@computer.id}", :text=> image_tag("icons/#{icon}.png",:title => icon.capitalize,:id=>"agent_state_#{@computer.id}")    
       end
       }
   
  end 
  
end
	# SWITCH_ROOM
	def switch_room

		@params = params

		id_tab = params[:id].split('_')
		id = id_tab[2]
		@computer = Computer.find(id)
		id_original = @computer.room_id
		id_new = params[:width].split('=')
		@computer.room_id = id_new[1]

		respond_to do |format|
			format.html {
				if @computer.save!
					redirect_to(computers_url)
				end
			}
			format.js {

				# update warning icon for each involved rooms
				if @computer.save!
					render :update do |page|

						# count events in original room
						original_sql = Computer.find_all_by_room_id(id_original,
										:joins => "	LEFT JOIN events ON computers.id = events.computer_id",
										:select => "count(events.id) AS count",
										:conditions => "events.state = 1 OR computers.state_computer = 0 OR computers.state_agent = 0",
										:group => "computers.id"
									)
						original_count = original_sql.count

						room_statut_original = "room_statut_#{id_original}"
						if original_count > 0
							page.replace_html room_statut_original, :text => image_tag("icons/warning.png", :title=>'Problème(s) en cours')
						else
							page.replace_html room_statut_original, :text => ''
						end

						# count events in new room
						new_sql = Computer.find_all_by_room_id(id_new[1],
										:joins => "	LEFT JOIN events ON computers.id = events.computer_id",
										:select => "count(events.id) AS count",
										:conditions => "events.state = 1 OR computers.state_computer = 0 OR computers.state_agent = 0",
										:group => "computers.id"
									)
						new_count = new_sql.count

						room_statut_new = 'room_statut_'+id_new[1]
						if new_count > 0
							page.replace_html room_statut_new, :text => image_tag("icons/warning.png", :title=>'Problème(s) en cours')
						else
							page.replace_html room_statut_new, :text => ''
						end
					end
				end
			}
		end
	end

	# PING
	def ping

		require 'ping'

		# get computer
		computer = Computer.find(params[:id])
		
		# ip to ping
		ip = computer.ip_computer

		# get status to compare after ping
		state_computer = computer.state_computer

		ping = Ping.pingecho(ip, 4)
		
		##### old
		# for linux user's
		#ping = IO.popen("ping -c 1 #{ip} | grep \"1 received\"").readlines

		# fix
		#if ping.nil?
		#	ping = []
		#end
		#####

		action_made = false # use in html view
		
		# if status are differents than ping.count
		if state_computer != ping
		
			# update each status in database
			computer.state_computer = ping # ping = false (0) or true (1)
			computer.save!

			# add event if not responding
			if !ping
				event_tab = {	"information" => "Hôte injoignable",
								"state" => 1,
								"computer_id" => params[:id],
								"type_event_id" => 3
							}
				event = Event.new(event_tab)

				event.save
			
			# mark event as finish
			else
				# TODO
				# be sure that everyone has the same id for unreachable host
				event = Event.find_all_by_computer_id(computer.id,
														:conditions => 'type_event_id = 3 AND information = "Hôte injoignable"',
														:order => 'id desc',
														:limit => 1);
				event[0].state = 0

				event[0].save

				@event = event[0]
			end

			action_made = true

		end

		### TODO ###
		### ASK EVERYONE IF OK ###
		
		# Everyone has to have same event.id_event_type for a type of event

		# event.state must have 0 value by default

		# if old status was NOK and is now OK
		# update last status event to OK
		
		### END ###

		respond_to do |format|
			
			format.html {
				@ping = ping
				@computer = computer
				@action_made = action_made
			}
			format.js {
				render :update do |page|
						
					# if status are differents than ping.count
					if state_computer != ping

						# update status icon
						if ping
							icon = "active"
						else
							icon = "inactive"
						end

						page.replace "computer_state_#{params[:id]}", 	:text => image_tag("icons/#{icon}.png",
																			:title=>icon.capitalize,
																			:id=>"computer_state_#{computer.id}",
																			:class=>'cursor_help')

					end
				end
			}
		end
	end

	def update_av

		now = Time.now.in_time_zone.to_s(:db)

		# one computer
		if params[:id].to_i.to_s == params[:id] || params[:id].to_f.to_s == params[:id]

			begin
				av_update = BaseVirale.find_by_computer_id(params[:id])

				if av_update != nil
					av_update.last_update = now
					av_update.save!

					success = true
				
				else
					@empty_list = true
				end

			rescue
				@error = true

			end

		# all computers
		else
			@test = true
			begin
				
				# select dates to update for all computers who are ok
				av_update = BaseVirale.find(	:all,
												:joins => 'INNER JOIN computers c ON c.id = base_virales.computer_id',
												:conditions => 'c.state_computer > 0',
												:readonly => false
											)
				if av_update.count > 0
					# update every selected date
					av_update.each do |av|
						av.last_update = now
						av.save!
					end

					success = true

				else
					@empty_list = true
				end

			rescue
				@error = true
			end
		end

		respond_to do |format|
			format.html {

			}
			format.js {
							
				# if success
				if success

					# update date only if single computer
					if params[:id].to_i.to_s == params[:id] || params[:id].to_f.to_s == params[:id]
						date_tab = now.split(' ')
						year, month, day = date_tab[0].split("-")
						date = "#{day}/#{month}/#{year} #{date_tab[1]}"

						render :update do |page|
							page.replace_html "av_update_#{params[:id]}", :text => date

							page.replace_html "av_update_statut", :text => image_tag("success.png",
																			:title=>"Erreur lors de la mise à jour des antivirus",
																			:class=>'cursor_help')
						end
					
					else 
						render :update do |page|
							page.replace_html "av_update_all", :text => image_tag("success.png",
																			:title=>"Erreur lors de la mise à jour des antivirus",
																			:class=>'cursor_help')
						end
					end

				else
					if params[:id].to_i.to_s == params[:id] || params[:id].to_f.to_s == params[:id]

							page.replace_html "av_update_statut", :text => image_tag("error.png",
																			:title=>"Erreur lors de la mise à jour des antivirus",
																			:class=>'cursor_help')
					else
						render :update do |page|
							page.replace_html "av_update_all", :text => image_tag("error.png",
																			:title=>"Erreur lors de la mise à jour des antivirus",
																			:class=>'cursor_help')
						end
					end

				end
			}
		end
	end

end
